import * as services from '@/services/global';
import { routerRedux } from 'dva';
import { message } from 'antd';

export default {
  namespace: 'global',
  state: {
    userMenuList: [],
    menusPath: [],
  },
  effects: {
    *query({ payload }, { call, put }) {},
    *login({ payload: params }, { call, put, select }) {
      //dispatch请求的方法
      // const { dataList } = yield select(state => state.system); //获取models中的state
      const result = yield call(services.login, params); //call,请求services里面的接口以及传参，可继续往后面加参数，跟JavaScript的call一样
      const { success, msg, data = {} } = result || {};
      const { token = '', userMenuList = [] } = data || {};
      const menusPath = userMenuList.map(
        (item) => '/administrators/admin' + item.menuPath,
      );
      yield put({
        //put,必须发出action save，此action被reducer监听，从而达到更新state数据的目的
        type: 'save',
        payload: { userMenuList: userMenuList, menusPath },
      });
      if (success) {
        yield localStorage.setItem('token', token);
        message.success('登录成功');
        yield;
        yield put(routerRedux.push('/administrators/admin/welcome'));
      } else {
        message.error(msg || '登录失败');
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    // 启用 immer 之后
    // save(state, action) {
    //   state.name = action.payload;
    // },
  },
  subscriptions: {
    // 订阅，在app.start()即启动项目时被执行
    setup({ dispatch, history }) {
      // return history.listen(({ pathname }) => {
      //   if (pathname === '/') {
      //     dispatch({
      //       type: 'query',
      //     })
      //   }
      // });
    },
  },
};
